package test;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.sun.org.apache.xerces.internal.util.Status;

import weibo4j.Place;
import weibo4j.Weibo;
import weibo4j.model.Places;
import weibo4j.model.StatusWapper;
import weibo4j.model.WeiboException;

public class UserTimelines extends Weibo {
	/**
	 * 程序主要是按照uid抓取其所有的签到动态。 1.主要是读取用户表中的uid终止的id是固定的。
	 * 2.假如程序崩掉了，更改起始的uid和token，注意最后抓完后要进行筛选下。
	 */
	private static final long serialVersionUID = 1L;
	private String access_token[] = new String[33];
	private DBConn db = new DBConn();
	private int pageLimit = 50;

	public UserTimelines() {
		access_token[0] = "2.00i_gE4CMLlPQDf42a44c1250fP99_";
		access_token[1] = "2.00i_gE4CTosKBE69d0127ea44fXcED";
		access_token[2] = "2.00i_gE4CmpTy_C8a3cddf65e45u4xD";
		access_token[3] = "2.00i_gE4CDdrAcC8e32dbf1bdW13XKE";
		access_token[4] = "2.00i_gE4C05c3VQ6f14ce7e1bR9EjTD";
		access_token[5] = "2.00i_gE4CF5GmrDb3ed1ad09eCHw_vD";
		access_token[6] = "2.00i_gE4Cwzl7MC92d2f4d7c2GFa23D";
		access_token[7] = "2.00i_gE4CWh1liB22cf8784d30T5R25";
		access_token[8] = "2.00i_gE4C0g1SIObaa6dc5ccb0Hn5n7";
		access_token[9] = "2.00i_gE4C6mzl9D019603e1ccUdpG_E";
		access_token[10] = "2.00Uu17fDMjsccBdc9ab6ae6c0_luH1";
		access_token[11] = "2.00Uu17fD2lkv2D5492d1e69dmwDbvC";
		access_token[12] = "2.00Uu17fD4yAhECdff0068244o34jCE";
		access_token[13] = "2.00Uu17fDa7JFPE31daa76b74arsGbD";
		access_token[14] = "2.00Uu17fDIsh3xC24739a2e640a8id9";
		access_token[15] = "2.00Uu17fDTHsKTD9d0693fda0q_ztZE";
		access_token[16] = "2.00Uu17fDCqn3MEa1ad0e70f6bkq4QB";
		access_token[17] = "2.00Me2rVDaCgTcEe1089fe19dRNO7kD";
		access_token[18] = "2.00Me2rVD7PEMhDf1ffe7336dFoFU4C";
		access_token[19] = "2.00Me2rVDBcro6E81c93eff01JmIsOB";
		access_token[20] = "2.00Me2rVDT7KHJD88e1655feefTzkKE";
		access_token[21] = "2.00YFodoFBSiemD77dee85a12xDt88B";
		access_token[22] = "2.00YFodoF0lcctOacaecd60a8x8FRWC";
		access_token[23] = "2.00joo_tCQicNqC5718b2e5fbT_jnSC";
		access_token[24] = "2.00joo_tC7MBPNE2ef3ca320d66JtVC";
		access_token[25] = "2.00joo_tCm2VVACa99fce513bBvGteD";
		access_token[26] = "2.00joo_tCpUeR9E5e34fc88b10lbPeT";
		access_token[27] = "2.00joo_tCxR7HyD043ba7228euXuo2C";
		access_token[28] = "2.00joo_tCvY9SdBf60f0e366endRsaD";
		access_token[29] = "2.00joo_tCtRbb5B9b889b929dYVMQDD";
		access_token[30] = "2.00joo_tCgHBjHB6820f00ee3c88aZD";
		access_token[31] = "2.00joo_tCbxytIDd1ef6bc6e43HIhPE";
		access_token[32] = "2.00joo_tC0YG1kEb955cccfe20use64";

		int idloop = 0;
		int tokenloop = 31;
		weibo4j.Place wp = new weibo4j.Place();
		wp.client.setToken(access_token[tokenloop]); // change the idloop
		long starttime = System.currentTimeMillis();
		long start = 1;// 0
		long end = 932933;// ;426078
		try {
			ResultSet rs = db.queryUID(start, end);
			while (rs.next()) {
				String uid = rs.getString(1);
//				 String uid = "2682394183";
				if (uid != null && !"null".equals(uid)) {
					int totalPage = 0;
					long totalwb = 0;
					int page = 1;
					do {
						if (idloop > 119) {
							if (tokenloop < 32) {
								// Thread.sleep(10000);
								tokenloop = tokenloop + 1;
								wp.client.setToken(access_token[tokenloop]);
								idloop = 0;
							} else {
								long costtime = System.currentTimeMillis()
										- starttime;
								if (costtime < 7200000) {
									System.out.println("wait...");
									Thread.sleep(7200000 - costtime);
								}
								tokenloop = 0;
								starttime = System.currentTimeMillis();
								idloop = 0;
								wp.client.setToken(access_token[tokenloop]);
								// page = totalPage+1;
							}
						}
						idloop = idloop + 1;
						// 获取用户签到过的地点列表， uid,单页返回的记录条数，默认为20，最大为50。返回结果的页数
						StatusWapper statuses = wp.userTimeLine(uid, pageLimit,
								page);
						if (statuses != null) {
							if (page == 1) {
								totalwb = totalPage = (int) statuses
										.getTotalNumber();
								;
								System.out
										.println(uid + "-totalck: " + totalwb);
								totalPage = (int) (totalwb / 50 + 1);
								Thread.sleep(1000);
							}
							// 一次抓50条
							List<weibo4j.model.Status> statuss = statuses
									.getStatuses();
							for (int i = 0; i < statuss.size(); i++) {
								weibo4j.model.Status lpi = statuss.get(i);
								String poiid = "";
								// 有的动态有POI，有的没有只有坐标所以需要分开 添加POI表
								if (lpi.getAnno() != null
										&& !"".equals(lpi.getAnno())
										&& lpi.getAnno().getPlace() != null
										&& !"".equals(lpi.getAnno().getPlace())) {
									weibo4j.model.Place place = lpi.getAnno()
											.getPlace();
									poiid = place.getPoi();

									if (poiid != null && !"".equals(poiid)
											&& !"null".equals(poiid)) {
										if (db.queryPoiId(poiid) == null) {
											insertPois(place);
										}
									}
								}
								int commentsCount = lpi.getCommentsCount();
								String geo = lpi.getGeo();
								double latitude = lpi.getLatitude();
								double lontitude = lpi.getLongitude();
								String text = lpi.getText();
								weibo4j.model.Source source = lpi.getSource();
								String sourceName = "";
								if (source != null && !"".equals(source)) {
									sourceName = source.getName();
								}

								Date dt = lpi.getCreatedAt();
								SimpleDateFormat sdf = new SimpleDateFormat(
										"yyyy-MM-dd HH:mm:ss");
								String createAt = sdf.format(dt);
								db.insertTimeLine(uid, poiid, commentsCount,
										geo, latitude, lontitude, text,
										sourceName, createAt);
								db.updateTimelineTime();// 更新时间周等基础表。

							}
							page = page + 1; // for the daily totalwb record
						} else {
							page = Integer.MAX_VALUE;
						}
					} while (page <= totalPage);
				}
				System.out.println("Stop at user: " + uid + ", tokenloop = "
						+ tokenloop);
			}
			db.close();
		} catch (WeiboException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private void insertPois(Places pl) {
		String regexp = "\'";
		String sTitle = pl.getTitle();
		String newTitle = sTitle.replaceAll(regexp, " ");
		String addr = pl.getpoiStreetAdds();
		String newAdd = addr.replaceAll(regexp, addr);
		String addr2 = pl.getpoiStreetAdds();
		String newAdd2 = addr2.replaceAll(regexp, addr2);
		db.insertPois(pl.getPoiid(), newTitle, newAdd, pl.getLon(),
				pl.getLat(), pl.getCategory(), pl.getCity(), pl.getProvince(),
				pl.getCountry(), pl.getCategorys(), pl.getCategoryName(),
				pl.getCheckinNum(), pl.getCheckinUserNum(), pl.getTipNum(),
				pl.getPhotoNum(), newAdd2);
	}

	private void insertPois(weibo4j.model.Place pl) {
		String regexp = "\'";
		String sTitle = pl.getTitle();
		String newTitle = sTitle.replaceAll(regexp, " ");

		db.insertPois(pl.getPoi(), newTitle, "", pl.getLongitude(),
				pl.getLatitude(), pl.getType(), "", "", "", "", "", 0, 0, 0, 0,
				"");
	}

	public static void main(String[] args) {
		UserTimelines dc = new UserTimelines();

	}

}
